<!--
 * @Author: folusGan 245942153@qq.com
 * @Date: 2024-07-09 15:42:24
 * @LastEditors: folusGan 245942153@qq.com
 * @LastEditTime: 2024-07-12 09:15:48
 * @Description: 
-->
<template>
  <div></div>
</template>
<script>
const isProd = process.env.VUE_APP_ENV === 'procuction'

const workcode = `onmessage = function (message) {
  if (${isProd}) {
    setInterval(
      () => {
        fetch(message.data + '/version', { cache: 'no-cache' }).then((data) => {
          data.text().then((rsp) => {
            postMessage(rsp)
          })
        })
      },
      ${!isProd} ? 60 * 60 * 3 : 60 * 60 * 30
    )
  }
}
`
export default {
  name: 'VersionNotify',
  data() {
    return {
      closeTime: null,
      notifyInstance: null,
    }
  },
  methods: {
    handleUpdate() {
      console.log('更新系统')
      const lang = localStorage.getItem('language')
      if (lang) localStorage.removeItem('language')
      window.location.reload()
    },
  },
  created() {
    console.log('notify组件创建')
    const workBlob = new Blob([workcode])
    const url = window.location.origin
    const worker = new Worker(URL.createObjectURL(workBlob))
    worker.postMessage(url)
    worker.onmessage = (e) => {
      if (!isProd) return
      console.log(e.data !== process.env.BUILD_AT, e.data, process.env.BUILD_AT)
      if (e.data !== process.env.BUILD_AT && !this.notifyInstance) {
        this.notifyInstance = this.$notify({
          title: '',
          duration: 0,
          showClose: false,
          position: 'bottom-right',
          onClose: () => {
            this.closeTime = new Date().getTime()
            this.notifyInstance = null
          },
          message: (
            <div style="height: 100px; display: flex; flex-direction: column">
              <div style="flex: 1; display: flex">
                <i
                  class="el-alert__icon el-icon-warning"
                  style="margin: 3px 6px 0 0"
                ></i>
                系统已更新，是否刷新页面加载最新版本？
              </div>
              <div style="text-align: right">
                <button
                  type="button"
                  class="el-button el-button--primaryel-button--mini"
                  onClick={() => {
                    this.handleUpdate()
                  }}
                >
                  <span> 确定 </span>
                </button>
                <button
                  type="button"
                  class="el-button el-button--primaryel-button--mini"
                  onClick={() => {
                    this.notifyInstance.close()
                  }}
                >
                  <span> 取消 </span>
                </button>
              </div>
            </div>
          ),
        })
      }
    }
  },
}
</script>
